package com.heima.comment.service.impl;

import com.heima.comment.service.ICommentService;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.CommentLikeMG;
import com.heima.model.comment.pojos.CommentMG;
import com.heima.model.comment.pojos.CommentRepayMG;
import com.heima.model.comment.vos.ResultLikesVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@RequiredArgsConstructor
public class CommentServiceImpl implements ICommentService {

    private final MongoTemplate mongoTemplate;


    /** 用户进行了文章评论提交 */
    @Override
    public ResponseResult save(CommentSaveDTO dto) {
        //判断是否是游客模式
        if(WmThreadLocalUtil.getUser().getId()==0){
            log.info("游客模式，不能评论");
            return new ResponseResult(500,"未登录,请先登录");
        }
        //进行文本内容字数检查有无超过140
        if(dto.getContent().length()>140){
            log.info("用户评论超过140字");
            return new ResponseResult(500,"评论不能超过140字");
        }
        //todo进行垃圾文本检测
        //进行数据补全
        CommentMG mg = new CommentMG();
        BeanUtils.copyProperties(dto,mg);
        WmUser user = WmThreadLocalUtil.getUser();
        mg.setEntryId(String.valueOf(dto.getArticleId()));
        mg.setAuthorName(user.getName());
        mg.setAuthorId(user.getId());
        mg.setCreatedTime(new Date());
        mg.setLikes(0);
        mg.setReply(0);
        mongoTemplate.save(mg);
        return ResponseResult.okResult("OK");
    }

    /** 进行了评论列表查询 */
    @Override
    public ResponseResult load(CommentDTO dto) {
        dto.setArticleId("1390536764510310401");
        log.info("分页查询开始：{},{},{},{}",dto.getArticleId(),WmThreadLocalUtil.getUser().getId(),dto.getIndex(),dto.getSize());
        // 创建分页请求
        Pageable pageable = PageRequest.of(dto.getIndex()-1, dto.getSize());
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()))
                .with(pageable)
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));

        // 查询所有评论
        List<CommentMG> commentMGS = mongoTemplate.find(query, CommentMG.class);
        //修改operation值 点赞数  评论数
        for (CommentMG commentMG : commentMGS) {
            log.info("commentMG.getId():{}",commentMG.getId());
            //修改operation值
            Query query1 = new Query();
            query1.addCriteria(Criteria.where("commentId").is(commentMG.getId()));
            query1.addCriteria(Criteria.where("authorId").is(String.valueOf(WmThreadLocalUtil.getUser().getId())));
            List<CommentLikeMG> commentMGS1 = mongoTemplate.find(query1, CommentLikeMG.class);
            if (commentMGS1.size()!=0){
                commentMG.setOperation(0);
            }else {
                commentMG.setOperation(null);
            }
            //修改点赞数
            Query query2 = new Query();
            query2.addCriteria(Criteria.where("commentId").is(commentMG.getId()));
            List<CommentLikeMG> commentMGS2 = mongoTemplate.find(query2, CommentLikeMG.class);
            commentMG.setLikes(commentMGS2.size());
            //修改评论数
            Query query3 = new Query();
            query3.addCriteria(Criteria.where("commentId").is(commentMG.getId()));
            List<CommentRepayMG> commentMGS3 = mongoTemplate.find(query2, CommentRepayMG.class);
            commentMG.setReply(commentMGS3.size());
        }
        log.info("分页查询结束:{}",commentMGS);
        return ResponseResult.okResult(commentMGS); // 创建分页结果
    }

    /** 进行了评论点赞 */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {

        //检查是否点赞过
        CommentMG mgO = mongoTemplate.findById(dto.getCommentId(), CommentMG.class);
        mgO.setOperation(dto.getOperation());
        if (dto.getOperation()==1){
            log.info("取消点赞:{}",mgO.getId());
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(String.valueOf(WmThreadLocalUtil.getUser().getId())).and("commentId").is(dto.getCommentId())),CommentLikeMG.class);
            log.info("取消点赞操作结束");
        }else if(dto.getOperation() == 0){
            log.info("进行点赞:{}",mgO.getId());
            CommentLikeMG mg = new CommentLikeMG();
            WmUser user = WmThreadLocalUtil.getUser();
            mg.setCommentId(dto.getCommentId());
            mg.setAuthorId(String.valueOf(user.getId()));
            mongoTemplate.save(mg);
            log.info("点赞操作结束");
        }

        Query query4 = new Query();
        query4.addCriteria(Criteria.where("commentId").is(dto.getCommentId()));
        List<CommentLikeMG> commentMGS = mongoTemplate.find(query4, CommentLikeMG.class);
        ResultLikesVO resultLikesVO = new ResultLikesVO(commentMGS.size());

        return ResponseResult.okResult(resultLikesVO);
    }
}
